package com.lxb.store.config;

import at.pollux.thymeleaf.shiro.dialect.ShiroDialect;
import com.lxb.store.shiro.UserRealm;
import org.apache.shiro.spring.web.ShiroFilterFactoryBean;
import org.apache.shiro.web.mgt.DefaultWebSecurityManager;
import org.springframework.beans.factory.annotation.Qualifier;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;

import java.util.LinkedHashMap;
import java.util.Map;

@Configuration
public class ShiroConfig {

    /**
     * 创建ShiroFilerFactoryBean
     */
    @Bean
    public ShiroFilterFactoryBean getShiroFilterFactoryBean(@Qualifier("securityManager") DefaultWebSecurityManager securityManager) {
        ShiroFilterFactoryBean shiroFilterFactoryBean = new ShiroFilterFactoryBean();

        //设置安全管理器
        shiroFilterFactoryBean.setSecurityManager(securityManager);

        //添加Shiro的内置过滤器
        /*
         * shiro内置过滤器，可以实现权限相关的拦截器
         * 常用的过滤器：
         * 	anon:无需认证（登录）可以访问
         * 	authc:必须认证才可以访问
         * 	user:如果remberMe的功能可以直接访问
         * 	perms:该资源必须得到资源权限访问
         * 	role:该资源必须得到角色权限才可以访问
         */
        Map<String, String> filterMap = new LinkedHashMap<>();

        //授权过滤器
        //filterMap.put("/user/add", "perms[user:add]");
        //filterMap.put("/user/update", "perms[user:update]");

        //拦截请求
        filterMap.put("/shopcar/**","authc");

        //不开启权限
        filterMap.put("/static/**", "anon");  //静态资源
        filterMap.put("/","anon");  //首页
        filterMap.put("/index","anon");  //首页
        filterMap.put("/register","anon"); //注册
        filterMap.put("/shop","anon");  //商品列表
        filterMap.put("/goods/**","anon");  //查看单个商品
        filterMap.put("/login","anon");

        filterMap.put("/auth/logout","logout");


        //开启权限


        //配置错误页面
        filterMap.put("/error","anon");  //错误页面


        //拦截之后跳转到登录页面
        shiroFilterFactoryBean.setLoginUrl("/login");

        //

        //设置未授权提示页面
        //shiroFilterFactoryBean.setUnauthorizedUrl("/noAuth");
        shiroFilterFactoryBean.setFilterChainDefinitionMap(filterMap);
        return shiroFilterFactoryBean;
    }

    /**
     * 创建DefaultWebSecurityManager
     */
    @Bean(name = "securityManager")
    public DefaultWebSecurityManager getDefaultWebSecurityManager(@Qualifier("userRealm") UserRealm userRealm) {
        DefaultWebSecurityManager securityManager = new DefaultWebSecurityManager();
        //关联realm
        securityManager.setRealm(userRealm);
        return securityManager;
    }

    /**
     * 创建Realm
     */
    @Bean(name = "userRealm")
    public UserRealm getRealm() {
        return new UserRealm();
    }

    /**
     * 配置ShiroDialect，用于thymeleaf和shiro标签配合使用
     */
    @Bean
    public ShiroDialect getShiroDialect() {
        return new ShiroDialect();

    }
}